﻿using DoNet.Common.Consts;
using DoNet.Common.Result;
using DoNet.Wechat.MP.Common;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace DoNet.Wechat.MP
{
    /// <summary>
    /// 微信公众平台access_token 
    /// </summary>
    public class AccessTokenMP
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger logger;
        /// <summary>
        /// 
        /// </summary>
        private readonly IServiceProvider serviceProvider;
        /// <summary>
        /// 缓存
        /// </summary>
        private readonly IMemoryCache memoryCache;
        /// <summary>
        /// 微信公众平台公共接口类
        /// </summary>
        private readonly CommonApi commonApi;
        /// <summary>
        /// 微信公众平台access_token
        /// </summary>
        /// <param name="_logger"></param>
        /// <param name="_serviceProvider"></param>
        public AccessTokenMP(ILogger _logger, IServiceProvider _serviceProvider)
        {
            logger = _logger;
            serviceProvider = _serviceProvider;
            commonApi = new CommonApi(logger, serviceProvider);
            memoryCache = serviceProvider.GetRequiredService<IMemoryCache>();
        }
        /// <summary>
        /// 获取微信公众平台access_token 
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        public CommonResult GetAccessToken(string appid, string secret)
        {
            CommonResult result = new CommonResult();
            string cacheKey = $"{CacheConst.WechatMPAccessToken}{appid}";
            var cacheAccessToken = memoryCache.Get(cacheKey);
            if (cacheAccessToken != null)
            {
                var tokenResultOld = (AccessTokenResult)cacheAccessToken;
                if (tokenResultOld != null)
                {
                    if (tokenResultOld.expire_time <= DateTime.Now)
                    {
                        //强制重新获取或者已过期，重新获取
                        var tokenResult = commonApi.GetToken(appid, secret);
                        if (tokenResult != null)
                        {
                            if (tokenResult.errcode == 0)
                            {
                                //先删除缓存
                                memoryCache.Remove(cacheKey);
                                //加入缓存
                                memoryCache.Set(cacheKey, tokenResult);
                                result.Success = true;
                                result.ResData = tokenResult.access_token;
                            }
                            result.ErrCode = tokenResult.errcode.ToString();
                            result.ErrCode = tokenResult.errmsg;
                        }
                    }
                    else
                    {
                        result.Success = true;
                        result.ResData = tokenResultOld.access_token;
                    }
                }
            }
            else
            {
                //强制重新获取或者已过期，重新获取
                var tokenResult = commonApi.GetToken(appid, secret);
                if (tokenResult != null)
                {
                    if (tokenResult.errcode == 0)
                    {
                        //加入缓存
                        memoryCache.Set(cacheKey, tokenResult);
                        result.Success = true;
                        result.ResData = tokenResult.access_token;
                    }
                    result.ErrCode = tokenResult.errcode.ToString();
                    result.ErrMsg = tokenResult.errmsg;
                }
            }
            return result;
        }
    }
}
